<?php

	function getClientIP(){ 
		if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ 
			$online_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; 
		}
		elseif(isset($_SERVER['HTTP_CLIENT_IP'])){ 
			$online_ip = $_SERVER['HTTP_CLIENT_IP']; 
		}
		elseif(isset($_SERVER['HTTP_X_REAL_IP'])){ 
			$online_ip = $_SERVER['HTTP_X_REAL_IP']; 
		}else{ 
			$online_ip = $_SERVER['REMOTE_ADDR']; 
		}
		$ips = explode(",",$online_ip);
		return $ips[0];  
	}
	    
	function http_post($payUrl, $data) {
		$webSite = empty ( $_SERVER ['HTTP_REFERER'] ) ? $_SERVER ['HTTP_HOST'] : $_SERVER ['HTTP_REFERER']; // 获取网站域名
		$options = array (
				'http' => array (
						'method'  => "POST",
						'header'  => "Accept-language:en\r\n"."Content-type:application/x-www-form-urlencoded\r\n".
	                		         "Content-Length:".strlen($data)."\r\n"."referer:".$webSite."\r\n",
						'content' => $data, 
						'timeout' => 90 
				) 
		); 
		$context = stream_context_create ( $options );
		return file_get_contents ( $payUrl, false, $context );
	}
		
	function curl_post($payUrl, $data) {
		$website = empty ( $_SERVER ['HTTP_REFERER'] ) ? $_SERVER ['HTTP_HOST'] : $_SERVER ['HTTP_REFERER']; // 获取网站域名
		$curl = curl_init ();
		curl_setopt ( $curl, CURLOPT_URL, $payUrl );
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
		curl_setopt ( $curl, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT'] );
		curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 );
		curl_setopt ( $curl, CURLOPT_REFERER, $website );
		curl_setopt ( $curl, CURLOPT_POST, 1 );
		curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
		curl_setopt ( $curl, CURLOPT_TIMEOUT, 90 );
		curl_setopt ( $curl, CURLOPT_HEADER, 0 );
		curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );	
		$result = curl_exec ( $curl );
		curl_close ( $curl );
		return $result;
	}
	
	//数据请求:Request data
	function send_gateway($payUrl, $data) {
		if (function_exists ( 'curl_init' ) && function_exists ( 'curl_exec' )) {
			return curl_post ( $payUrl, $data ); 
		} else {
			return http_post( $payUrl, $data ); 
		}
	}
	
	
	$merNo                      = trim($_POST['merNo']);           
	$terNo                      = trim($_POST['terNo']);              
	$orderAmount                = trim($_POST['orderAmount']);          
	$orderCurrency              = trim($_POST['orderCurrency']);    
	$orderNo                    = trim($_POST['orderNo']);                 
	$billCountry                = trim($_POST['billCountry']);     
	$billState                  = trim($_POST['billState']);       
	$billCity                   = trim($_POST['billCity']);        
	$billAddress                = trim($_POST['billAddress']);     
	$billZip                    = trim($_POST['billZip']);     
	$billEmail                  = trim($_POST['billEmail']);     
	$billPhone                  = trim($_POST['billPhone']);   
	$billFirstName              = trim($_POST['billFirstName']);    
	$billLastName               = trim($_POST['billLastName']);          
	$shipCountry                = trim($_POST['shipCountry']);       
	$shipState                  = trim($_POST['shipState']);         
	$shipCity                   = trim($_POST['shipCity']);          
	$shipAddress                = trim($_POST['shipAddress']);       
	$shipZip                    = trim($_POST['shipZip']);       
	$shipEmail                  = trim($_POST['shipEmail']);         
	$shipPhone                  = trim($_POST['shipPhone']);   
	$shipFirstName              = trim($_POST['shipFirstName']); 
	$shipLastName               = trim($_POST['shipLastName']);                   
	$cardNo                     = trim($_POST['cardNo']);          
	$cardExpireYear             = trim($_POST['cardExpireYear']);         
	$cardExpireMonth            = trim($_POST['cardExpireMonth']);        
	$cardSecurityCode           = trim($_POST['cardSecurityCode']);           
	$ip                         = trim($_POST['ip']); 
	$webSite                    = trim($_POST['webSite']);
	$returnUrl                  = trim($_POST['returnUrl']);
	$notifyUrl                  = trim($_POST['notifyUrl']);            
	$userAgent                  = trim($_POST['userAgent']);        
	$acceptLang                 = trim($_POST['acceptLang']);
	$client                     = trim($_POST['client']);
	$goodsInfo                  = urldecode(trim($_POST['goodsInfo']));  
	$remark                     = trim($_POST['remark']);  
	$signKey                    = trim($_POST['signKey']); 
	
    //请求加密数据(Sha256):SHA256 encrypted payment request data
    //数据组合/Data combination：merNo+terNo+orderNo+orderCurrency+orderAmount+cardNo+cardExpireYear+cardExpireMonth+cardSecurityCode+signKey
	$str                        = $merNo.$terNo.$orderNo.$orderCurrency.$orderAmount.$cardNo.$cardExpireYear.$cardExpireMonth.$cardSecurityCode.$signKey;
	$signInfo                   = hash('sha256',$str);		
	
	//支付交易参数/Transaction related data
	$data = array (
			'cardNo'           => $cardNo,
			'cardSecurityCode' => $cardSecurityCode,
			'cardExpireMonth'  => $cardExpireMonth,
			'cardExpireYear'   => $cardExpireYear,
			'merNo'            => $merNo,
			'terNo'            => $terNo,
			'orderNo'          => $orderNo,
			'orderAmount'      => $orderAmount,
			'orderCurrency'    => $orderCurrency,
			'billFirstName'    => $billFirstName,
			'billLastName'     => $billLastName,
			'billEmail'        => $billEmail,
			'billPhone'        => $billPhone,
			'billZip'          => $billZip,
			'billAddress'      => $billAddress,
			'billCity'         => $billCity,
			'billState'        => $billState,
			'billCountry'      => $billCountry,
			'shipFirstName'    => $shipFirstName,
			'shipLastName'     => $shipLastName,
			'shipPhone'        => $shipPhone,
			'shipEmail'        => $shipEmail,
			'shipCountry'      => $shipCountry,
			'shipState'        => $shipState,
			'shipCity'         => $shipCity,
			'shipAddress'      => $shipAddress,
			'shipZip'          => $shipZip,
			'returnUrl'        => $returnUrl,
			'notifyUrl'        => $notifyUrl,
			'webSite'          => $webSite,
			'signInfo'         => $signInfo,
			'client'           => $client,
			'ip'               => $ip,
			'acceptLang'       => $acceptLang,
			'userAgent'        => $userAgent,
			'goodsInfo'        => $goodsInfo,
			'remark'           => $remark
	);
	//发送银行/send bank
	$returnData  = http_post("https://security.ssltopay.com/direct",http_build_query ($data, '', '&' ));
	$result      = json_decode($returnData,true);
	if(isset($result) && !empty($result) && is_array($result)) {
		//Sha256加密支付返回数据:SHA256 encrypted payment result data 
		//数据组合/Data Combination: merNo + terNo + tradeNo + orderNo + orderCurrency + orderAmount +orderSucceed + signKey
		$str     = $result['merNo'].$result['terNo'].$result['tradeNo'].$result['orderNo'].$result['orderCurrency'].$result['orderAmount'].$result['orderSucceed'].$signKey;
		$mySign  = strtoupper(hash('sha256',$str));	
		
		//判断支付结果/Determine The Payment Result
		if($mySign == $result['signInfo']) {
		    if($result['orderSucceed'] == '1'){ 
		    	//支付成功/Payment Success
		    	echo "Transaction successful !";
		    }else if($result['orderSucceed'] == '-1' || $result['orderSucceed'] == '-2'){
		    	//支付处理中/Payment Processing
		    	echo "Transaction processing !";
			    $redirect = $result['redirectURL'];
			    //注意：待处理时,如果重定向地址:redirectURL 不为空时,则表示交易还未完成,必须把地址进行重定向出去,最终支付结果将跳转到returnUrl页面。
			    //如果重定向地址(redirectURL)为空,此时支付结果为最终结果，将不会跳转到returnUrl页面
			    //Note: When pending,if the redirectURL value is not empty, it means that the transaction has not been completed, the address must be redirected out, and the final payment result will be redirected to the returnUrl page.
				//If the redirectURL value is empty,it means payment result has been completed, and it will not be redirected to the returnUrl page.
			    if(isset($redirect) && !empty($redirect) && $redirect != 'null'){
					header("Location: $redirect");
					exit();
				}
		    }else if($result['orderSucceed'] == '0'){ 
		    	//支付失败/Payment Failure
		    	echo "Transaction failure,the reason is :" . $result['orderResult'];
		    }else{
		    	//未知支付结果/Unknown Payment Result
		    	echo "Unknown result !";
		    }
		}else{
			//数据校验失败/Date Verification Failed
			echo "Data verification failed !";
		} 
	}else{
		//连接银行异常/Can not connect bank
		echo "Bank connect exception !";
	}

?>